/**
 * @Auther: adminyhk
 * @Date: 2018/11/20 13:30
 * @Description:
 */

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;

import java.io.IOException;

public class HandlerHBase {

    private static final String TABLE_NAME = "qqq";
    private static final String ZK_ADDRESS = "127.0.0.1:2181";

    public static void main(String[] args) throws IOException {
        createData("userId-1".getBytes(), "routeId-1".getBytes(), "drivingSpeed".getBytes(), "500km/h".getBytes());
        System.out.println("=====================插入完毕==============");
        System.out.println(getData("userId-1".getBytes(), "routeId-1".getBytes(), "drivingSpeed".getBytes()));
    }

    public static void createData(byte[] rowKey, byte[] family, byte[] colum, byte[] value) throws IOException {
        Configuration config = HBaseConfiguration.create();
        config.set(HConstants.ZOOKEEPER_QUORUM, ZK_ADDRESS);
        TableName tn = TableName.valueOf(TABLE_NAME);
        try (Connection connection = ConnectionFactory.createConnection(config);
             Table table = connection.getTable(tn);) {
            HTableDescriptor tableDescriptor = new HTableDescriptor(tn);
            tableDescriptor.addFamily(new HColumnDescriptor(family));
            Admin admin = connection.getAdmin();
            if (!admin.tableExists(tn)) {
                admin.createTable(tableDescriptor);
            }
            Put put = new Put(rowKey);
            put.addColumn(family, colum, value);
            table.put(put);
        }


    }

    public static String getData(byte[] rowKey, byte[] family, byte[] colum) throws IOException {
        Configuration config = HBaseConfiguration.create();
        config.set(HConstants.ZOOKEEPER_QUORUM, ZK_ADDRESS);
        TableName tn = TableName.valueOf(TABLE_NAME);
        try (Connection connection = ConnectionFactory.createConnection(config);
             Table table = connection.getTable(tn);) {
            HTableDescriptor tableDescriptor = new HTableDescriptor(tn);
            tableDescriptor.addFamily(new HColumnDescriptor(family));
            Admin admin = connection.getAdmin();
            if (!admin.tableExists(tn)) {
                admin.createTable(tableDescriptor);
            }
            Get get = new Get(rowKey);
            Result r = table.get(get);
            byte[] value = r.getValue(family, colum);
            return new String(value);
        }
    }
}